package selfProgram.StepZero;

import java.io.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;

/*1.读取文件并测试是否读取成功*/
/*2.将字母分类的插入到数组中，并统计字母数目*/
/*3.查询每个字母出现的频率*/
public class StepZero {
    public static void main(String[] args) {
        /*获取文本文件*/
        File f=new File("C:\\Users\\zqzdidiannao\\Desktop\\codebaby\\softProject\\resources\\file.txt");
        Reader reader;

        int time [] = new int[27];
        for (int i = 1; i < 27; i++) {
            time[i] =0;
        }

        try{
            try {
                reader = new InputStreamReader(new FileInputStream(f));
                int tempchar;

                while((tempchar = reader.read())!=-1){
                    if ((tempchar-96)>0 && (tempchar-96)<27){
                        time[tempchar-96]++;
                    }
                    if((tempchar-64)>0 && (tempchar-64)<27){
                        time[tempchar-64]++;
                    }
                }
                /*将获取的文件打印出来*/
//                while((tempchar = reader.read()) != -1){
//                    if (((char) tempchar) != '\r') {
//                        System.out.print((char) tempchar);
//                    }
//                }
                reader.close();
                int sum=0;
                for (int i = 1; i < 27; i++) {
                    sum+=time[i];
                }
                System.out.println("总词数为："+sum);
                /*计算出每个单词的出现频率*/
                double rate[] = new double[27];
                DecimalFormat df = new DecimalFormat("#.00");
                for (int i = 1; i < 27; i++) {
                    double temp = (float)time[i]/sum*100;
                    rate[i]= Double.parseDouble(df.format(temp));
//                    rate[i] = (double)(Math.round((float)time[i]/sum*100)/100);
//                    rate[i] = new BigDecimal((float)time[i]/sum).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                }

                /*存放每一个输出语句*/
                String rs[] = new String[27];
                for (int i = 1; i < 27; i++){
                    rs[i]="字母"+(char)(i+96)+"出现了"+time[i]+"次"+"出现的频率为"+rate[i]+"%";
                }
                for (int i = 1; i < 27; i++){
                    System.out.println(rs[i]);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        finally {

        }

    }
}
